package com.xiaocg.base.thread.pool;


import java.util.Random;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author xiaocg
 */
public class SynchronizedTest {

    private static Random random = new Random();

    public static void main(String[] args)throws Exception {
        Account account1 = new Account(10000);
        Account account2 = new Account(10000);

        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                account1.transfer(account2,getRandom());
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                account2.transfer(account1,getRandom());
            }
        });

        t1.start();
        t2.start();
        System.out.println("main join");
        t1.join();
        t2.join();
        System.out.println("account total:"+(account1.getMoney()+account2.getMoney()));
        ReentrantLock reentrantLock = new ReentrantLock();
    }

    private static int getRandom(){
        return random.nextInt(10)+1;
    }
}

class Account{
    private int money;

    public Account(int money) {
        this.money = money;
    }

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }

    public void transfer(Account account,int amount){
        synchronized (Account.class) {
            if (this.money > amount) {
                this.setMoney(this.money - amount);
                account.setMoney(account.getMoney() + amount);
            }
        }
    }
}
